package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.UserTaskApply;
import com.ruoyi.system.mapper.UserTaskApplyMapper;
import com.ruoyi.system.service.IUserTaskApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserTaskApplyServiceImpl implements IUserTaskApplyService {
    @Autowired
    private UserTaskApplyMapper userTaskApplyMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public boolean hasUserApplied(Long userId, Long taskId) {
        return userTaskApplyMapper.selectByUserIdAndTaskId(userId, taskId) != null;
    }

    @Override
    @Transactional
    public int applyTask(Long userId, Long taskId) {
        if (hasUserApplied(userId, taskId)) return 0;
        UserTaskApply apply = new UserTaskApply();
        apply.setUserId(userId);
        apply.setTaskId(taskId);
        userTaskApplyMapper.insertUserTaskApply(apply);
        return 1;
    }

    @Override
    public int countApplyByTaskId(Long taskId) {
        return userTaskApplyMapper.countByTaskId(taskId);
    }

    @Override
    public java.util.List<Long> selectTaskIdsByUserId(Long userId) {
        return userTaskApplyMapper.selectTaskIdsByUserId(userId);
    }

    @Override
    public int cancelApplyTask(Long userId, Long taskId) {
        return userTaskApplyMapper.deleteByUserIdAndTaskId(userId, taskId);
    }

    @Override
    public int countByUserId(Long userId) {
        return userTaskApplyMapper.countByUserId(userId);
    }

    @Override
    public List<SysUser> getApplicantsForTask(Long taskId) {
        List<Long> userIds = userTaskApplyMapper.selectUserIdsByTaskId(taskId);
        if (userIds == null || userIds.isEmpty()) {
            return new ArrayList<>();
        }
        return sysUserService.selectUserListByIds(userIds);
    }
} 